# -*- coding: utf-8 -*-
"""
******* 文档说明 ******
API 微服务后台代码

# 当前项目: API-Demo
# 创建时间: 2019-08-04  12:35
# 开发作者: vincent
# 创建平台: PyCharm
# 版   本: V1.0
"""
from flask import Flask
from flask import request
import numpy as np
import base64
import hashlib
import json
import os

app = Flask(__name__)


# UTF-8 编码格式
@app.route('/test', methods=['POST'])
def test():
    print('----------------------------------------------')
    # print('{:12s}: {}'.format('Method', request.method))
    # print('{:12s}: {}'.format('URL', request.url))
    # print('{:12s}: {}'.format('params', request.args))
    # print('{:12s}: {}'.format('Header', request.headers))
    # print('{:12s}: {}'.format('Form', request.form))
    # print('{:12s}: {}'.format('Data', request.data))
    # print('{:12s}: {}'.format('JSON', request.json))

    # 传输图片Hash值
    image_hash = hashlib.md5(request.data).hexdigest()

    # 图片大小
    image_height = int(request.args['ImageHeight'])
    image_width = int(request.args['ImageWidth'])
    image_channl = int(request.args['ImageChannl'])

    # 图片解码
    image_data = np.array(list(base64.b64decode(request.data)), dtype='uint8')
    # ReShape
    image_data = np.reshape(image_data, (image_height, image_width, image_channl))

    # # 保存图片
    # import cv2
    # cv2.imencode(".jpg", image_data)[1].tofile('demo.jpg')

    # ###################### 图片处理计算
    image_predict_result = {'Result': 'DemoSuccess'}

    # ###################### 返回响应结果
    response = {'Predict': image_predict_result,
                'ImageHash': image_hash,
                'ImageShape': image_data.shape}
    response = json.dumps(response, ensure_ascii=False, sort_keys=True, indent=4)
    print(response)
    print('----------------------------------------------')
    # 返回请求数据
    return response


# 计算文件 MD5 哈希值
def get_file_md5(filename, batch_size=8096):
    """
    :param filename:    文件路径
    :param batch_size:  每批次读取大小
    :return:  返回文件 MD5 值，若文件不存在则返回None
    """

    if not os.path.isfile(filename):
        return None

    file_hash = hashlib.md5()
    f = open(filename, 'rb')
    while True:
        b = f.read(batch_size)
        if not b:
            break
        file_hash.update(b)
    f.close()
    return file_hash.hexdigest()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5588, debug=False)
